<?php
namespace PsiFramework\Applications\DefaultApp\Classes\Actions\User;

import("Classes.Actions.AbstractAction");
import("Classes.Model.ModelInterface.IUser");
import("Classes.Util.Object.EMail");
import("Classes.Util.UI.HTML");
import("Classes.Util.Manager.ParametersManager");
import("Plugins.Recaptcha.Classes.Tools.Captcha");

use \PsiFramework\Classes\Actions\AbstractAction;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Factory\ObjectFactory;
use \PsiFramework\Classes\Model\ModelInterface\IUser;
use \PsiFramework\Classes\Util\Object\Date;
use \PsiFramework\Classes\Util\Object\EMail;
use \PsiFramework\Classes\Util\Object\Image;
use \PsiFramework\Classes\Util\UI\HTML;
use \PsiFramework\Classes\Util\Manager\ParametersManager;
use \PsiFramework\Plugins\Recaptcha\Classes\Tools\Captcha;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The Register Action
 *
 * This action is used when a user wants to create an account
 *
 * @package Actions.User
 */
class RegisterAction extends AbstractAction
{

    /**
     * Function executed by the controller
     *
     * It shows the register form or registers a user
     *
     * @param    User        $user    the user to display
     * @return     Response    the response to the action execution
     */
    public function execute(/*User*/ $user=null, /*string*/ $error=null)
    {

        if ($this->_request->getParameter("login")!=null
            && $this->_request->getParameter("password")!=null
            && $user===null
        ) {
            //if form has been submitted

            //creates a new user
            $user = ObjectFactory::getNewObject("User");
            $user->setLogin($this->_request->getParameter("login"));
            //encrypts the password
            $user->setPassword(md5($this->_request->getParameter("password")));

            //sets the other variables of the user
            if ($this->_request->getParameter("email") != null) {

                //set the birth date
                if ($this->_request->getParameter("yearOfBirth") != null
                    && $this->_request->getParameter("monthOfBirth") != null
                    && $this->_request->getParameter("dayOfBirth") != null
                ) {
                    $birthDate = new Date(
                        $this->_request->getParameter("yearOfBirth"),
                        $this->_request->getParameter("monthOfBirth"),
                        $this->_request->getParameter("dayOfBirth")
                    );
                    $user->setBirth($birthDate);
                }

                //set the email
                $user->setEmail($this->_request->getParameter("email"));

                //retrieve the city by id
                $cityId = $this->_request->getParameter("city");
                if ($cityId!=null) {
                    $cityDao = DAOFactory::getDAO("City");
                    $city = $cityDao->retrieveByPk($cityId, false, false);
                    $user->setCity($city);
                }

                //retrieve the gender
                $genderId = $this->_request->getParameter("gender");
                if ($genderId!=null) {
                    $genderDao = DAOFactory::getDAO("Gender");
                    $gender = $genderDao->retrieveByPk($genderId, false, false);
                    $user->setGender($gender);
                }

                //retrieve the picture
                $file = $this->_request->getFile("pictureName");
                if ($file != null) {
                    $image = new Image($file);
                    //creates an id for the image
                    $imageName = uniqid("", true).".".$file->getExtension();
                    //resize the image
                    $image->createResizedPictures($imageName);

                    $user->setPicture($imageName);
                } else if ($this->_request->getParameter("oldPictureName") != null) {
                    //if there's an old picture
                    $user->setPicture(
                        $this->_request->getParameter("oldPictureName")
                    );
                }

            } else {
                //if the parameters weren't all present
                $user = null ;
            }

            if ($user != null) {
                $user->setCreationDate(Date::now());

                if ($pwd = $this->_request->getParameter("confirmPassword")) {
                    //if the password has been entered twice the same

                    $captcha = Captcha::getInstance();
                    if ($captcha->retrieveResponse()) {
                        //if the captcha response is ok

                        $userDao = DAOFactory::getDAO("User");
                        //saves the user
                        $ok = $userDao->save($user, true, false);

                        if ($ok) {
                            //if the database request succeeded

                            //creation of the activation code
                            $activationCode = uniqid();
                            $activation
                                = ObjectFactory::getNewObject("Activation");
                            $activation->setUser($user);
                            $activation->setActivationKey($activationCode);
                            $activationDao = DAOFactory::getDAO("Activation");
                            //saving of the activation object
                            $ok
                                = $activationDao->save(
                                    $activation, true, false
                                );

                            if ($ok) {
                                //if the database request succeeded

                                $paramManager
                                    = ParametersManager::getInstance();
                                $applicationsParameters
                                    = $paramManager->getApplicationsParameters();

                                $link  = $this->_request->getHostURI();
                                $link .= 
                                    "?action=User.ConfirmRegistration&".
                                    "activationKey=".$activationCode ;
                                
                                $email = new EMail(
                                    $applicationsParameters->getContact(),
                                    $user->getEmail(),
                                    "Confirm Registration",
                                    HTML::link($link, $link)
                                );
                                //send email to the user
                                $email->send();
                                //display the confirm registration form
                                $this->findForward('success');
                            }
                        } else {
                            //if there has been a database error
                            //display the registration form anew
                            $this->execute($user, "Database Error !");
                        }
                    } else {
                        //captcha error
                        $this->execute(
                            $user,
                            "Captcha error : ".$captcha->getError()
                        );
                    }
                } else {
                    //different passwords
                    $this->execute($user, "Password error !");
                }
            } else {
                //different passwords
                $this->execute($user, "Information error !");
            }
        } else {

            $country = null ;
            //if the user has specified his city,
            //we retrieve the country it's in
            if ($user != null && $user->getCity() != null) {
                $country = $user->getCity()->getSubdivision()->getCountry();
            }

            $cityDao = DAOFactory::getDAO("City"); ;
            $countryDao = DAOFactory::getDAO("Country"); ;
            $genderDao = DAOFactory::getDAO("Gender"); ;

            $cities = array();
            if ($country != null) {
                //if the country is specified, we
                //get all the cities for that country
                $cities = $cityDao->getAllCities($country);
            }
            //we retrieve all the countries
            $countries = $countryDao->retrieveAll(null, null, false);
            //we retrieve all the genders
            $genders = $genderDao->retrieveAll(null, null, false);

            //we set the parameters to be shown to the user
            $this->_response->setAttribute("user", $user);
            $this->_response->setAttribute("cities", $cities);
            $this->_response->setAttribute("countries", $countries);
            $this->_response->setAttribute("genders", $genders);
            $this->_response->setAttribute("action", "Register");
            $this->_response->setAttribute("captcha", Captcha::getInstance());
            $this->_response->setAttribute("error", $error);

            $this->findForward('form');
        }
    }

}
